﻿using System;
using System.Text;
using System.Threading;
using System.Timers; 
using System.Collections.Specialized;
using System.Threading.Tasks;
using Quartz.Impl;
using Quartz;
using Quartz.Logging;
using Quartz.Impl.Matchers;
using static Quartz.MisfireInstruction; 
  
namespace ParkingDataSimulate
{
    public partial class ParkingDataSimulateTask
    {
        public static bool Stop { get; set; }
        public static int IntervalSeconds { get; set; }
        public static string NumberPlate { get; set; }
        public static async Task RunSecondlyGlobalProgram(int intervalSeconds)
        {
            IntervalSeconds = intervalSeconds;
            DateTime startTime = DateTime.Now.AddSeconds(intervalSeconds);

#if DEBUG
            startTime = DateTime.Now;
#endif 
            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                IScheduler scheduler = await factory.GetScheduler();

                await scheduler.Start();

                IJobDetail job = JobBuilder.Create<ScheduleSecondlyGlobalJob>()
                    .WithIdentity("JOB1_SIMULATE", "GROUP_JOB1_SIMULATE")
                    .Build();
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("TRIGGER1_SIMULATE")
                    .StartAt(startTime)  
                    .ForJob("JOB1_SIMULATE", "GROUP_JOB1_SIMULATE").WithSimpleSchedule(t => t.WithIntervalInSeconds(intervalSeconds).RepeatForever())
                    .Build();
                

                string loggerLineMonthly = $"[1][FUNC::ParkingDataSimulateTask.RunSecondlyGlobalProgram] [RUN SIMULATE]";
                 Console.WriteLine(loggerLineMonthly);

                await scheduler.ScheduleJob(job, trigger);
                 
                await Task.Delay(TimeSpan.FromMilliseconds(2000));
                 
            }
            catch (SchedulerException se)
            {
                string loggerLineMonthly = $"[1][EXCEPTION::SchedulerException][FUNC::ScheduleGlobal.RunSecondlyGlobalProgram][{se.Message}][{se.StackTrace}]";
                await Console.Error.WriteLineAsync(loggerLineMonthly);
            }
        }

        public class ScheduleSecondlyGlobalJob : IJob
        { 
            public Task Execute(IJobExecutionContext context)
            {
                if (!Stop)
                {
                    VAXTORJson vAXTOR = VAXTORJson.Get(1);
                    if (string.IsNullOrEmpty(vAXTOR.Plate))
                    {
                        vAXTOR.Plate = NumberPlate ?? "AB1C1";
                    }

                    var timeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");

                    vAXTOR.Date = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}+08:00";
                    vAXTOR.OccuredDatetime = DateTime.Now;
                    vAXTOR.Image64 = VAXTORBASE.Image64;
                    if(DateTime.Now.Minute % 10 == 0 || DateTime.Now.Minute % 10 == 1 || DateTime.Now.Minute % 10 == 2 || DateTime.Now.Minute % 10 == 3)
                    {
                        return Console.Out.WriteLineAsync(string.Format("\n[1][{0:yyyy-MM-dd HH:mm:ss fff}] [PASS] [FUNC::ScheduleSecondlyGlobalJob.Execute] [{1}][PASS] [PASS][{2}][{3}]", DateTime.Now, context.FireInstanceId, vAXTOR.Plate, vAXTOR.Ip));
                    }
                    else
                    {
                        PublicTest.ParkingEntryXPost(vAXTOR);
                        return Console.Out.WriteLineAsync(string.Format("\n[1][{0:yyyy-MM-dd HH:mm:ss fff}] [INFO] [FUNC::ScheduleSecondlyGlobalJob.Execute] [{1}][{2}][{3}]", DateTime.Now, context.FireInstanceId, vAXTOR.Plate, vAXTOR.Ip));
                    }  
                }
                else
                {
                    return Console.Out.WriteLineAsync(string.Format("\n[1][{0:yyyy-MM-dd HH:mm:ss fff}] [STOP] [ScheduleSecondlyGlobalJob] [{1}][Stop={2}]", DateTime.Now, context.FireInstanceId, Stop));
                }
            }
        }
    }
}